<template>
    <div class="app-container">
    <div class="filter-container">
      <el-form>
        <el-form-item>
          <el-button type="danger" icon="el-icon-add" @click="showCreate" v-if="hasPerm('package:add')">添加
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="5">
        <p style="color: #989A9A;">套餐名</p>
        <el-input placeholder="输入套餐名" v-model="searchParam.packageName" @keyup.enter.native="getList('search')"></el-input>
      </el-col>

      <el-col :span="4">
        <p>&nbsp;</p>
        <el-button type="danger" @click="getList('search')">搜索</el-button>
      </el-col>

    </el-row>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit
              highlight-current-row>
      <el-table-column align="center" label="序号" width="80">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)"> </span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="packageName" label="套餐名" width="160" sortable></el-table-column>
      <el-table-column align="center" label="套餐内容" width="160" prop="content">
      </el-table-column>
      <el-table-column align="center" label="图片" style="width: 60px;">
          <template slot-scope="scope">
              <img :src="scope.row.avatar" width="100" height="100"/>
          </template>
      </el-table-column>
      <el-table-column align="center" prop="price" label="价格" width="160" :formatter="priceFormatter" sortable></el-table-column>
      <el-table-column align="center" prop="score" label="评分" width="160" sortable></el-table-column>
      <el-table-column align="center" prop="description" label="菜品描述" style="width: 60px;"></el-table-column>
      <el-table-column align="center" label="管理" width="200px" v-if="hasPerm('package:edit')">
        <template slot-scope="scope">
          <el-button type="danger" icon="el-icon-edit" @click="showUpdate(scope.$index)" size="small">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="handleDelete(scope.$index)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="listQuery.pageNum"
      :page-size="listQuery.pageSize"
      :total="totalCount"
      layout="prev, pager, next">
    </el-pagination>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form v-if="dialogStatus=='update'" class="small-space" label-position="left" label-width="70px"
               style='width: 500px; margin-left:50px;'>
        <el-form-item label="套餐名">
          <el-input type="text" v-model="tempArticle.packageName">
          </el-input>
        </el-form-item>
        <el-form-item>
            <span>选择菜品</span>
            <div class="lk-toolbar" v-for="(name, key) in children" :key="key">
              <el-row :gutter="30">
                <el-col :span="10">
                  <span>菜品名</span>
                  <el-input readonly v-model="name.dishesVo.dishesName"></el-input>
                </el-col>
                <el-col :span="10">
                  <span>数量</span>
                  <el-input type="number" min="0.0" max="99.0" step="1" v-model="name.amount"/>
                </el-col>
                <el-col :span="4">
                  <span>&nbsp;</span>
                  <el-button size="small" @click="deleteItem(key)" type="text">删除菜品</el-button>
                </el-col>
              </el-row>
          </div>
          <el-row :gutter="30">
            <el-col :span="10">
              <span>菜品名</span>
                <el-select v-model="newDishes.id"
                      filterable
                      remote
                      reserve-keyword
                      :remote-method="transformDishesList"
                      :loading="loading">
                <el-option 
                    v-for="item in dishesListOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="10">
              <span>数量</span>
              <el-input type="number" min="0.0" max="99.0" step="1" v-model="newDishes.amount"/>
            </el-col>
        </el-row>
          <el-button size="small" type="danger" @click="addApplication">添加菜品</el-button>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            :action="doUpload"
            list-type="picture"
            :on-success="handleAvatarSuccess"
            :show-file-list="showFileList">
            <img v-if="tempArticle.avatar" :src="tempArticle.avatar" width="250" height="250" class="avatar">
            <el-button size="small" type="danger" v-if="! tempArticle.avatar">点击上传</el-button>
            <div slot="tip" class="el-upload__tip" v-if="! tempArticle.avatar">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="tempArticle.description">
          </el-input>
        </el-form-item>
      </el-form>

      <!--华丽的分割线 -->

      <el-form v-else class="small-space" :model="tempArticle" label-position="left" label-width="70px"
               style='width: 500px; margin-left:50px;'>
        <el-form-item label="套餐名">
          <el-input type="text" v-model="tempArticle.packageName">
          </el-input>
        </el-form-item>
        <el-form-item>
            <span>选择菜品</span>
            <div class="lk-toolbar" v-for="(name, key) in children" :key="key">
              <el-row :gutter="30">
                <el-col :span="10">
                  <span>菜品名</span>
                  <el-input readonly v-model="name.dishesVo.dishesName"></el-input>
                </el-col>
                <el-col :span="10">
                  <span>数量</span>
                  <el-input type="number" min="0.0" max="99.0" step="1" v-model="name.amount"/>
                </el-col>
                <el-col :span="4">
                  <span>&nbsp;</span>
                  <el-button size="small" @click="deleteItem(key)" type="text">删除菜品</el-button>
                </el-col>
              </el-row>
          </div>
          <el-row :gutter="30">
            <el-col :span="10">
              <span>菜品名</span>
                <el-select v-model="newDishes.id"
                      filterable
                      remote
                      reserve-keyword
                      :remote-method="transformDishesList"
                      :loading="loading">
                <el-option 
                    v-for="item in dishesListOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="10">
              <span>数量</span>
              <el-input type="number" min="0.0" max="99.0" step="1" v-model="newDishes.amount"/>
            </el-col>
        </el-row>
          <el-button size="small" type="danger" @click="addApplication">添加菜品</el-button>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            :action="doUpload"
            list-type="picture"
            :on-success="handleAvatarSuccess"
            :show-file-list="showFileList">
            <img v-if="tempArticle.avatar" :src="tempArticle.avatar" width="250" height="250" class="avatar">
            <el-button size="small" type="danger" v-if="! tempArticle.avatar">点击上传</el-button>
            <div slot="tip" class="el-upload__tip" v-if="! tempArticle.avatar">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="tempArticle.description">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCancel">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="danger" @click="createArticle">创 建</el-button>
        <el-button type="danger" v-else @click="updateArticle">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
    data() {
      return {
        doUpload: '/pos/img',
        imageUrl: '',//'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        showFileList: false,
        totalCount: 0, //分页组件--数据总条数
        list: [],//表格的数据
        listLoading: false,//数据加载等待动画
        listQuery: {
          pageNum: 1,//页码
          pageSize: 15,//每页条数
        },
        searchParam: {
          packageName: '',
          dishesName:'' 
        },
        children: [],
        newDishes: {},
        tempChildren: [],
        dialogStatus: 'create',
        dialogFormVisible: false,
        textMap: {
          update: '编辑',
          create: '添加套餐'
        },
        tempArticle: {
          dishesName: '',
          typeName: '',
          dishesTypeId: 0,
          avatar: ''
        },
        dishesList: [],
        dishesListOption: [],
        state: [],
        loading: false,
        deleteDialogShow: false
      }
    },
    created() {
      this.getList()
    },
    mounted() {
      this.getDishesList()
    },
    methods: {
      addApplication() {
        const temp = {
          dishesVo: {
            id: this.newDishes.id.value,
            dishesName: this.newDishes.id.label,
          },
          amount: this.newDishes.amount
        }
        if (typeof(temp.dishesVo.dishesName) === 'undefined' || temp.dishesVo.dishesName === '') {
          this.$message.error('请完整填写菜品名')
          return;
        }
        if (typeof(temp.amount) === 'undefined' || temp.amount === '') {
          this.$message.error('请填写菜品数量')
          return;
        }
        let exist
        this.children.forEach((item, index) => {
          if (item.dishesVo.dishesName === temp.dishesVo.dishesName) {
            this.$message.error('该菜品已在套餐中')
            exist = true
          }
        })
        if(! exist) {
          this.children.push(temp)
          this.newDishes = {}
        }
      },
      deleteItem(key) {
        this.children.splice(key, 1)
      },
      priceFormatter(row, column) {
        return '￥' + row.price
      },
      dialogCancel() {
        this.dialogFormVisible = false
        this.tempArticle = {
        }
      },
      handleAvatarSuccess(res, file) {
        this.tempArticle.avatar = res.data;
        this.$emit('done', this.tempArticle.avatar)
      },
      async getDishesList() {
        const res = await this.$api.dishes.list('1', '1', false)
        this.state = data.data
          this.dishesList = this.state.map(item => {
              return { value: item.id, label: item.dishesName };
          });;
      },
      transformDishesList(query) {
        if (query !== '') {
          this.loading = true;
          setTimeout(() => {
              this.loading = false;
              this.dishesListOption = this.dishesList.filter(item => {
                  return item.label.toLowerCase()
                    .indexOf(query.toLowerCase()) > -1;
              });
          }, 200);
        } else {
          this.dishesListOption = [];
        }
      },
      async getList(search) {
        //查询列表
        if (!this.hasPerm('dishes:list')) {
          return
        }
        this.listLoading = true
        const res = (search && search === 'search') ? 
          await this.$api.packageDishes.search(this.listQuery.pageSize, this.listQuery.pageNum, this.searchParam) : 
          await this.$api.packageDishes.list(this.listQuery.pageSize, this.listQuery.pageNum, true)
        this.listLoading = false
        this.list = res.data.data
        this.list.forEach((item, index) => {
            let str = ''
            item.dishesInfo.forEach((dishes, i) => {
              str += dishes.dishesVo.dishesName + ' * ' + dishes.amount + ' '
            })
            item.content = str
          })
        this.totalCount = res.data.total
      },
      handleSizeChange(val) {
        //改变每页数量
        this.listQuery.pageRow = val
        // this.handleFilter();
      },
      handleCurrentChange(val) {
        //改变页码
        this.listQuery.pageNum = val
        this.getList();
      },
      getIndex($index) {
        //表格序号
        return (this.listQuery.pageNum - 1) * this.listQuery.pageSize + $index + 1
      },
      showCreate() {
        //显示新增对话框
        this.tempArticle = {}
        this.children = []
        this.tempArticle.type = 1
        this.dialogStatus = "create"
        this.dialogFormVisible = true
      },
      showUpdate($index) {
        this.tempArticle = JSON.parse(JSON.stringify(this.list[$index]))
        this.children = JSON.parse(JSON.stringify(this.list[$index].dishesInfo))
        this.dialogStatus = "update"
        this.dialogFormVisible = true
      },
      handleDelete($index) {
        let _vue = this;
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确认',
          showCancelButton: false,
          type: 'warning'
        }).then(async () => {
          let dishes = _vue.list[$index]
          await _vue.$api.packageDishes.delete(dishes.id)
          _vue.$message.success('删除成功')
          _vue.getList()
        })
      },
      async createArticle() {
        this.tempArticle.dishesInfo = this.children
        await this.$api.packageDishes.add(this.tempArticle)
        this.getList()
        this.dialogFormVisible = false
      },
      async updateArticle() {
        this.tempArticle.dishesInfo = this.children
        await this.$api.packageDishes.edit(this.tempArticle)
        this.getList()
        this.dialogFormVisible = false
        this.fileList = []
      },
    }
}
</script>

<style>

</style>
